import fs from 'fs'
import { reflectRule } from './mysqlreflect.js'
import { formatToHump } from './utils.js'
let config = {}
export const createValidate = (columns, tableName) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    config = JSON.parse(data)
    // field{columnName:comment}
    const humpTableName = formatToHump(tableName)
    const folder = `${config.vendorFolder}/${humpTableName}`
    // verify file is exist or not
    const fileName = `${folder}/validate.ts`
    if (fs.existsSync(fileName)) {
    // file is exist
      console.log(`======file is existed and ignore to created validate:${tableName}=======`)
    } else {
      let validates = '\t'
      const length = columns.length
      for (const i in columns) {
        validates += `${columns[i].columnName}: [${reflectRule(columns[i])}]`
        if (Number(i) !== length - 1) {
          validates += ',\n\t'
        }
      }
      if (!fs.existsSync(folder)) {
        fs.mkdirSync(folder, { recursive: true }, (err) => {
          if (err) throw err
        })
      }
      // console.log('validates:',validates)
      const content = `export const validate:any = {\n${validates}\n}`
      fs.writeFile(fileName, content, { flag: 'a' }, (err) => {
        if (err) {
          console.log('========error======')
          throw err
        } else {
          console.log(`======succeessfully created validate:${tableName}=======`)
        }
      })
    }
  })
}
